//
//  DetailViewController.m
//  kyMusicPlayer
//
//  Created by 翁科宇 on 2018/5/17.
//  Copyright © 2018年 翁科宇. All rights reserved.
//

#import "DetailViewController.h"

@interface DetailViewController ()
{
    MusicPlayerManager *musicPlayer;
    SongInfo *songInfo;
}
@end

@implementation DetailViewController
//在类初始化中配置子视图,防止songInfo.mTimeArray数组没有创建,导致程序崩溃
- (instancetype)init{
    self = [super init];
    if (self) {
        [self configSubView];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self getShuffleAndRepeatState];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self playStateRecover];
}
#pragma mark - configSubView
- (void)configSubView{
    // 初始化musicPlayer和songInfo
    musicPlayer = MusicPlayerManager.sharedManager;
    songInfo = SongInfo.sharedManager;
    // top view初始化
    _topView = [[TopView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 5)];
    [_topView.backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_topView];
    // mid view 初始化
    _midView = [[MidView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 5, self.view.frame.size.width, self.view.frame.size.height / 5 * 3)];
    [self.view addSubview:_midView];
    // bottom view 初始化
    _bottomView = [[BottomView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 5 * 4, self.view.frame.size.width, self.view.frame.size.height / 5)];
    [self.view addSubview:_bottomView];
     // SongListView初始化
    
    
    // 添加playOrPauseButton响应事件
    [_bottomView.playOrPauseBtn addTarget:self action:@selector(playOrPauseBtnAction) forControlEvents:UIControlEventTouchUpInside];
    // 添加nextSongButton响应事件
    [_bottomView.nextSongBtn addTarget:self action:@selector(nextSongBtnAction) forControlEvents:UIControlEventTouchUpInside];
    // 添加preButton响应事件
    [_bottomView.preSongBtn addTarget:self action:@selector(preSongBtnAction) forControlEvents:UIControlEventTouchUpInside];
    //添加播放模式响应事件
    [_bottomView.playModeBtn addTarget:self action:@selector(playModeBtnAction) forControlEvents:UIControlEventTouchUpInside];
    // 添加songListButton响应事件
    
    
    // 播放进度条添加响应事件
    [_bottomView.songSlider addTarget:self action:@selector(playbackSliderValueChanged) forControlEvents:UIControlEventValueChanged];
    [_bottomView.songSlider addTarget:self action:@selector(playbackSliderValueChangedFinish) forControlEvents:UIControlEventTouchUpInside];
    // 设置背景图片
    [self setBackgroundImage:[UIImage imageNamed:@"backgroundImage3"]];
}

- (void)playStateRecover{
    [_midView.midIconView.imageView startRotating];
    if (musicPlayer.play.rate == 1) {
        NSLog(@"播放!");
        [_bottomView.playOrPauseBtn setImage:[UIImage imageNamed:@"cm2_fm_btn_pause"] forState:UIControlStateNormal];
        [_bottomView.playOrPauseBtn setImage:[UIImage imageNamed:@"cm2_fm_btn_pause_prs"] forState:UIControlStateHighlighted];
        [_midView.midIconView.imageView resumeRotate];
    }
    else{
        NSLog(@"暂停!");
        [_bottomView.playOrPauseBtn setImage:[UIImage imageNamed:@"cm2_fm_btn_play"] forState:UIControlStateNormal];
        [_bottomView.playOrPauseBtn setImage:[UIImage imageNamed:@"cm2_fm_btn_play_prs"] forState:UIControlStateHighlighted];
        [_midView.midIconView.imageView stopRotating];
    }
}

#pragma - mark 设置detail控制界面背景图片
- (void)setBackgroundImage:(UIImage *)image{
    _backgroundImgView = [[UIImageView alloc] initWithFrame:CGRectMake(-ScreenWith / 2, - ScreenHeight / 2, ScreenWith * 2, ScreenHeight * 2)];
    _backgroundImgView.image = image;
    _backgroundImgView.clipsToBounds = YES;
    [self.view addSubview:_backgroundImgView];
    [self.view sendSubviewToBack:_backgroundImgView];
    // 毛玻璃效果
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *visualView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    visualView.alpha = 1.0;
    visualView.frame = CGRectMake(- ScreenWith / 2, -ScreenHeight / 2, ScreenWith * 2, ScreenHeight * 2);
    visualView.clipsToBounds = YES;
    [_backgroundImgView addSubview:visualView];
    
}

#pragma - mark 播放或暂停
- (void)playOrPauseBtnAction{
    if (musicPlayer.play.rate == 0) {
        NSLog(@"播放!");
        [_bottomView.playOrPauseBtn setImage:[UIImage imageNamed:@"cm2_fm_btn_pause"] forState:UIControlStateNormal];
        [_bottomView.playOrPauseBtn setImage:[UIImage imageNamed:@"cm2_fm_btn_pause_prs"] forState:UIControlStateHighlighted];
        [_midView.midIconView.imageView resumeRotate];
        [musicPlayer startplay];
    }else{
        NSLog(@"暂停!");
        [_bottomView.playOrPauseBtn setImage:[UIImage imageNamed:@"cm2_fm_btn_play"] forState:UIControlStateNormal];
        [_bottomView.playOrPauseBtn setImage:[UIImage imageNamed:@"cm2_fm_btn_play_prs"] forState:UIControlStateHighlighted];
        [_midView.midIconView.imageView stopRotating];
        [musicPlayer stopplay];
    }
}

#pragma - mark 下一曲
- (void)nextSongBtnAction{
    musicPlayer.playingIndex = songInfo.playSongIndex;
    switch (musicPlayer.shuffleAndRepeatState) {
        case RepeatPlayMode:{//顺序播放
            
            musicPlayer.playingIndex ++;
            if (musicPlayer.playingIndex >= songInfo.mSongs.count) {//最后一首了
                musicPlayer.playingIndex = 0; //跳到第一首
            }
        }
            break;
        case RepeatOnlyOnePlayMode:{//单曲循环
            
        }
            break;
        case ShufflePlayMode:{//随机播放
            if (musicPlayer.playingIndex == songInfo.mSongs.count - 1) {
                musicPlayer.playingIndex = [self getRandomNumber:0 with:(songInfo.mSongs.count - 2)];//重头开始不包括本首歌
            }else{
                musicPlayer.playingIndex = [self getRandomNumber:(musicPlayer.playingIndex + 1) with:(songInfo.mSongs.count - 1)];
            }
        }
            break;
        default:
            break;
    }
    
    if (musicPlayer.playingIndex != songInfo.playSongIndex) {
        if (songInfo.playSongIndex < songInfo.mSongs.count) {
            HotSongInfo *info = songInfo.mSongs[musicPlayer.playingIndex];
            NSLog(@"即将播放下一首歌曲: 《%@》",info.title);
            [songInfo setSongInfo:info];
            [songInfo getSelectedSong:info.song_id index:songInfo.playSongIndex + 1];
        }
    }else{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"repeatPlay" object:self];
    }
}

#pragma - mark 上一曲
- (void)preSongBtnAction{
    musicPlayer.playingIndex = songInfo.playSongIndex;
    switch (musicPlayer.shuffleAndRepeatState) {
        case RepeatPlayMode:{
            if (musicPlayer.playingIndex == 0) {//第一首
                musicPlayer.playingIndex = songInfo.mSongs.count - 1;//跳到最后一首
            }else{
                musicPlayer.playingIndex --; //索引为上一首
            }
        }
            break;
        case RepeatOnlyOnePlayMode:{
            
        }
            break;
        case ShufflePlayMode:{
            if (musicPlayer.playingIndex == 0) {//是第一首歌
                musicPlayer.playingIndex = [self getRandomNumber:1 with:(songInfo.mSongs.count - 1)];//播放除第一首歌之外的所有歌曲(即从第2首到最后一首)
            }else{
                musicPlayer.playingIndex = [self getRandomNumber:0 with:(musicPlayer.playingIndex - 1)];
            }
        }
            break;
        default:
            break;
    }
    
    if (musicPlayer.playingIndex != songInfo.playSongIndex) {
        if (songInfo.playSongIndex > 0) {
            HotSongInfo *info = songInfo.mSongs[songInfo.playSongIndex - 1];
            NSLog(@"即将播放上一首歌曲: 《%@》", info.title);
            [songInfo setSongInfo:info];
            [songInfo getSelectedSong:info.song_id index:songInfo.playSongIndex - 1];
        }
    }else{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"repeatPlay" object:self];
    }
    
}

#pragma - mark 播放模式按键action
- (void)playModeBtnAction{
    switch (musicPlayer.shuffleAndRepeatState) {
        case RepeatPlayMode:{
            [_bottomView.playModeBtn setImage:[UIImage imageNamed:@"cm2_icn_one"] forState:UIControlStateNormal];
            [_bottomView.playModeBtn setImage:[UIImage imageNamed:@"cm2_icn_one_prs"] forState:UIControlStateHighlighted];
            musicPlayer.shuffleAndRepeatState = RepeatOnlyOnePlayMode;// 单曲循环
            [self showMiddleHint:@"单曲循环"];
        }
            break;
        case RepeatOnlyOnePlayMode:{
            [_bottomView.playModeBtn setImage:[UIImage imageNamed:@"cm2_icn_shuffle"] forState:UIControlStateNormal];
            [_bottomView.playModeBtn setImage:[UIImage imageNamed:@"cm2_icn_shuffle_prs"] forState:UIControlStateHighlighted];
            musicPlayer.shuffleAndRepeatState = ShufflePlayMode;// 列表播放
            [self showMiddleHint:@"列表播放"];
        }
            break;
        case ShufflePlayMode:{
            [_bottomView.playModeBtn setImage:[UIImage imageNamed:@"cm2_icn_loop"] forState:UIControlStateNormal];
            [_bottomView.playModeBtn setImage:[UIImage imageNamed:@"cm2_icn_loop_prs"] forState:UIControlStateHighlighted];
            musicPlayer.shuffleAndRepeatState = RepeatPlayMode;// 随机播放
            [self showMiddleHint:@"随机播放"];
        }
        default:
            break;
    }
    //存储路径
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:musicPlayer.shuffleAndRepeatState] forKey:@"SHFFLEANDREPEATSTATE"];
}

#pragma - mark 获取保存的播放模式
- (void)getShuffleAndRepeatState{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSNumber *repeatAndShuffleNumber = [defaults objectForKey:@"SHFFLEANDREPEATSTATE"];
    if (repeatAndShuffleNumber == nil) {
        musicPlayer.shuffleAndRepeatState = RepeatPlayMode;
    }
    else{
        musicPlayer.shuffleAndRepeatState = (ShuffleAndRepeatState)[repeatAndShuffleNumber integerValue];
    }
    
    [self settingState];
}
#pragma mark - 下滑退出detail控制界面
- (void)responseGlide{
    [self settingState];
    //
}
#pragma - mark 设置播放模式
- (void)setShuffleAndRepeatState{
    [self settingState];
    //存储路径
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:musicPlayer.shuffleAndRepeatState] forKey:@"SHFFLEANDREPEATSTATE"];
}
#pragma - mark 进度条改变值时触发
- (void)playbackSliderValueChanged{
    //更新播放时间
    [self updateTime];
     //如果当前时暂停状态，则自动播放
    if (musicPlayer.play.rate == 0) {
        [_bottomView.playOrPauseBtn setImage:[UIImage imageNamed:@"cm2_fm_btn_pause"] forState:UIControlStateNormal];
        [_bottomView.playOrPauseBtn setImage:[UIImage imageNamed:@"cm2_fm_btn_pause_prs"] forState:UIControlStateHighlighted];
        [_midView.midIconView.imageView resumeRotate];
        [musicPlayer startplay];
    }
}
#pragma - mark 进度条改变值结束时触发
- (void)playbackSliderValueChangedFinish{
    //更新播放时间
    [self updateTime];
    //如果当前时暂停状态，则自动播放
    if (musicPlayer.play.rate == 0) {
        [_bottomView.playOrPauseBtn setImage:[UIImage imageNamed:@"cm2_fm_btn_pause"] forState:UIControlStateNormal];
        [_bottomView.playOrPauseBtn setImage:[UIImage imageNamed:@"cm2_fm_btn_pause_prs"] forState:UIControlStateHighlighted];
        [_midView.midIconView.imageView resumeRotate];
        [musicPlayer startplay];
    }
}



//MARK:抽取播放模式功能代码
- (void)settingState{
    switch (musicPlayer.shuffleAndRepeatState) {
        case RepeatPlayMode:{
            [_bottomView.playModeBtn setImage:[UIImage imageNamed:@"cm2_icn_loop"] forState:UIControlStateNormal];
            [_bottomView.playModeBtn setImage:[UIImage imageNamed:@"cm2_icn_loop_prs"] forState:UIControlStateHighlighted];
        }
            break;
        case RepeatOnlyOnePlayMode:{
            [_bottomView.playModeBtn setImage:[UIImage imageNamed:@"cm2_icn_one"] forState:UIControlStateNormal];
            [_bottomView.playModeBtn setImage:[UIImage imageNamed:@"cm2_icn_one_prs"] forState:UIControlStateHighlighted];
        }
            break;
        case ShufflePlayMode:{
            [_bottomView.playModeBtn setImage:[UIImage imageNamed:@"cm2_icn_shuffle"] forState:UIControlStateNormal];
            [_bottomView.playModeBtn setImage:[UIImage imageNamed:@"cm2_icn_shuffle_prs"] forState:UIControlStateHighlighted];
        }
            break;
        default:
            break;
    }
}

- (void)backAction{
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - 播放模式提示框
- (void)showMiddleHint:(NSString*)hint{
    MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hub.userInteractionEnabled = NO;
    hub.mode = MBProgressHUDModeText;
    hub.label.font = [UIFont systemFontOfSize:15];
    hub.label.text = hint;
    hub.margin = 10.f;
    hub.offset = CGPointMake(0.f, 0.f);
    hub.removeFromSuperViewOnHide = YES;
    [hub hideAnimated:YES afterDelay:2.f];
}


#pragma - mark 获取随机数，用于随机播放
- (NSInteger)getRandomNumber:(NSUInteger)from with:(NSUInteger)to{//包括两边边界
    NSUInteger res = from + (arc4random() % (to - from + 1));
    return res;
}

#pragma - mark 更新播放时间
- (void)updateTime{
    CMTime duration = musicPlayer.play.currentItem.asset.duration;
    // 歌曲总时间和当前时间
    Float64 completeTime = CMTimeGetSeconds(duration);
    Float64 currentTime = (_bottomView.songSlider.value) * completeTime;
    //播放器定位到对应的位置
    CMTime targetTime = CMTimeMake((int64_t)currentTime, 1);
    [musicPlayer.play seekToTime:targetTime];
    
    int index = 0;
    for (NSString *indexstr in songInfo.mTimeArray) {
        if ((NSInteger)currentTime < [songInfo stringToInt:indexstr]) {
            songInfo.lrcIndex = index;
        }
        else{
            index = index + 1;
        }
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
